/*
 *  $Id: Conditional.cs 437 2008-10-09 12:51:09Z thenn.erannor $
 *	This file is a part of Ragima CCG.
 *	(C) 2008 Ragima development group.
 *
 *	Licensed under the terms of the GNU GPL License version 2.
 *
 */

namespace Ragima {
    /// <summary>
    /// Абстрактный условный эффект: включается по определенному условию 
    /// </summary>
    public abstract class ConditionalAffect: GroupAffect {
        private bool _enabled;

        public ConditionalAffect(): base() {
            _enabled = false;
        }

        public override void SetAffect() {
            base.SetAffect();
            RegisterEvents();
            Update();
        }
        public override void ResetAffect() {
            base.ResetAffect();
            UnregisterEvents();
        }

        public void Update() {
            bool enabled = IsEnabled();
            if (enabled == _enabled) return;
            _enabled = enabled;
            ResetAffects();
            if (enabled)
                AddAffects();
            else
                Clear();
            SetAffects();
        }

        protected abstract bool IsEnabled();
        protected abstract void AddAffects();
        protected virtual void RegisterEvents() {}
        protected virtual void UnregisterEvents() {}
    }

    public abstract class GameObjectsConditionalAffect: ConditionalAffect {
        protected override void RegisterEvents() {
            Player player = Owner.Owner;
            RegisterEvents(player);
            RegisterEvents(player.Enemy);
        }
        protected override void UnregisterEvents() {
            Player player = Owner.Owner;
            UnregisterEvents(player);
            UnregisterEvents(player.Enemy);
        }

        private void RegisterEvents(Player player) {
            player.GlobalSummary.OnCreatureSummon += DoCreatureSummon;
            player.GlobalSummary.OnLandSummon += DoLandSummon;
            player.GlobalSummary.OnDeath += DoDeath;
        }
        private void UnregisterEvents(Player player) {
            player.GlobalSummary.OnCreatureSummon -= DoCreatureSummon;
            player.GlobalSummary.OnLandSummon -= DoLandSummon;
            player.GlobalSummary.OnDeath -= DoDeath;
        }

        private void DoCreatureSummon(Creature creature) {
            Update();
        }
        private void DoLandSummon(Land land) {
            Update();
        }
        private void DoDeath(AbstractObject obj) {
            Update();
        }
    }
}